<!--
 * @Description  : 
 * @Autor        : guoxi
 * @Date         : 2022-06-29 14:08:57
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-08-05 14:09:08
 * @FilePath     : \rpms\src\views\document\scientific\building\index.vue
-->
<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="科技制度建设" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box form-box">
      <el-form
        :disabled="!isEdit"
        :model="model.formData"
        ref="formRef"
        @submit.prevent
        :rules="model.formRules"
        label-width="160px"
      >
        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="成果来源" prop="paperType">
              <el-select
                style="width: 100%"
                v-model="model.formData.paperType"
                clearable
                placeholder="请选择"
                value-key="id"
              >
                <el-option
                  v-for="(item, index) in model.paperTypes"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="科技制度名称" prop="scientificSystemName">
              <el-input
                v-model.trim="model.formData.scientificSystemName"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="model.formData.paperType === '1'">
          <el-col :xl="8" :lg="12">
            <el-form-item label="所属项目" placeholder="请选择所属项目">
              <el-select
                style="width: 100%"
                v-model="model.formData.projectId"
                clearable
                placeholder="请选择"
                value-key="id"
                @change="handleSelected"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="项目编号" prop="projectNum">
              <el-input
                disabled
                v-model.trim="model.formData.projectNum"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="科技制度类型" prop="scientificSystemType">
              <el-select
                v-model="model.formData.scientificSystemType"
                clearable
                style="width: 100%"
                value-key="dicCode"
              >
                <el-option
                  v-for="item in model.buildingTypes"
                  :key="item.key"
                  :label="item.label"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="颁布时间" prop="publishTime">
              <el-date-picker
                style="width: 100%"
                v-model="model.formData.publishTime"
                value-format="YYYY-MM-DD hh:mm:ss"
                type="date"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="所属公司主体" prop="principalCompanyCode">
              <el-select
                v-model="model.formData.principalCompanyCode"
                clearable
                style="width: 100%"
                value-key="dicCode"
              >
                <el-option
                  id="default-option"
                  v-for="item in principalCompanyArr"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="上传文档" prop="attachment">
              <el-upload
                name="uploadFile"
                multiple
                :accept="acceptTypes"
                :action="uploadComUrl"
                :headers="uploadHeaders"
                :on-success="handleSuccess"
                :on-remove="handleRemove"
                :on-error="handleError"
                :file-list="defaultFileList"
                :before-upload="beforeAvatarUpload"
                :on-preview="handlePreview"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
// import { useRoute } from "vue-router";
import { addSystem, updateSystem, getSystemById } from "/@/api/document";
import { postProjectList } from "/@/api/project";
import { useUpload } from "/@/hooks";
import NotifMessage from "/@/utils/message/notification";

import { useRoute, useRouter } from "vue-router";
import { postDictList } from "/@/api/common";

const router = useRouter();
const route = useRoute();
let model = reactive({
  mode: "Add",
  dialogFormVisible: false,
  data: [],
  loading: false,
  paperTypes: [
    { name: "项目", value: "1" },
    { name: "非项目", value: "2" }
  ],
  formData: {
    principalCompanyCode: "",
    paperType: "",
    projectNum: "",
    projectId: null,
    scientificSystemName: "",
    scientificSystemType: "",
    publishTime: "",
    attachment: []
  },
  buildingTypes: [
    { key: "基础制度", label: "基础制度" },
    { key: "成果转化", label: "成果转化" },
    { key: "知识产权管理", label: "知识产权管理" },
    { key: "创新激励", label: "创新激励" },
    { key: "创新考核", label: "创新考核" },
    { key: "创新人才", label: "创新人才" }
  ],

  formRules: {
    paperType: [
      { required: true, message: "请选择成果来源", trigger: "change" }
    ],
    scientificSystemName: [
      { required: true, message: "请输入科技制度名称", trigger: "change" }
    ],

    scientificSystemType: [
      { required: true, message: "请选择科技制度类型", trigger: "change" }
    ],

    publishTime: [
      { required: true, message: "请选择颁布时间", trigger: "change" }
    ],
    author: [{ required: true, message: "请选择作者", trigger: "change" }],
    principalCompanyCode: [
      { required: true, message: "请选择所属公司主体", trigger: "change" }
    ]
    // authorDeptName: [
    //   { required: true, message: "请输入作者单位", trigger: "change" }
    // ],
    // authorRank: [
    //   { required: true, message: "请输入作者排名", trigger: "change" }
    // ],

    // attachment: [{ required: true, message: "请上传附件", trigger: "change" }]
  }
});
const {
  handleError,
  beforeAvatarUpload,
  uploadComUrl,
  acceptTypes,
  uploadHeaders
} = useUpload();
const formRef = ref<HTMLFormElement | null>(null) as any;
// const deptTreePartakeRef = ref<HTMLElement | null>(null) as any;

let projectList = ref([]);
let defaultFileList = ref([]);
let principalCompanyArr = ref([]);

const initPrincipalCompanyList = async () => {
  try {
    const params = {
      dicType: "rd_principal_cmpy"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      principalCompanyArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectList({ pageNum: 1, pageSize: 0 });
    if (code === 200) {
      projectList.value = data.list;
      model.formData.projectNum = data.list.find(
        el => el.id === model.formData.projectId
      )?.projectCode;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
  model.formData.attachment = model.formData.attachment.filter(item => {
    const uuid = file.response ? file.response.data.uuidFile : file.uuidFile;
    return item.uuidFile !== uuid;
  });
};

const handleSuccess = (res, file, fileList) => {
  if (res.code === 200) {
    nextTick(() => {
      defaultFileList.value = fileList;
      model.formData.attachment.push(res.data);
    });
  }
  formRef.value.clearValidate();
};

const handlePreview = (item: any) => {
  if (item.response) {
    window.open(
      `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
    );
  } else {
    window.open(
      `${location.origin}${location.pathname}#/online?uuidFile=${item.uuidFile}&fileName=${item.fileName}`
    );
  }
};
const handleSelected = item => {
  const target = projectList.value.find(el => el.id === item);
  model.formData.projectNum = target.projectCode;
};
const handleSubmit = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;

  const params = JSON.parse(JSON.stringify(model.formData));
  params.attachment = JSON.stringify(params.attachment);
  if (model.formData.paperType === "2") {
    params.projectId = null;
    params.projectNum = null;
  }
  if (model.mode === "Add") {
    const { code, message } = await addSystem(params);
    if (code === 200) {
      goback();
      NotifMessage.success("保存成功");
    } else {
      NotifMessage.error(message);
    }
  } else {
    const { code, message } = await updateSystem(params);
    if (code === 200) {
      goback();
      NotifMessage.success("保存成功");
    } else {
      NotifMessage.error(message);
    }
  }
};

const goback = () => {
  router.push("/document/scientific");
};
const getData = async id => {
  defaultFileList.value = [];
  const { data } = await getSystemById(id);

  model.formData = data;
  model.formData.attachment = JSON.parse(model.formData.attachment as any);
  defaultFileList.value = model.formData.attachment;
  defaultFileList.value.map(el => {
    el["name"] = el.fileName;
  });
  model.formData.paperType = data.projectId ? "1" : "2";
  // model.formData.projectNum = route.query.projectNum as any;
};
const isEdit = route.query.mode === "edit" ? true : false;
const id = route.query.id;
if (id) {
  model.mode = "Edit";
  getData(id);
}
getProjectList();
initPrincipalCompanyList();
</script>

<style lang="scss" scoped>
.content {
  .card-box--headerwrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-box--setbtn {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 140px;
  }
}
</style>
